{% extends 'dashboard/base.html' %}
{% load static %}

{% block title %}活动管理 - 后台管理{% endblock %}

<style>
    .table-responsive {
        border-radius: 0.5rem;
    }

    .table > :not(caption) > * > * {
        padding: 0.75rem 0.5rem;
    }

    .btn-group-sm > .btn {
        border-radius: 0.25rem;
        margin: 0 2px;
    }

    /* 状态徽章美化 */
    .badge.bg-success { background: linear-gradient(45deg, #28a745, #20c997) !important; }
    .badge.bg-warning { background: linear-gradient(45deg, #ffc107, #fd7e14) !important; }
    .badge.bg-danger { background: linear-gradient(45deg, #dc3545, #e83e8c) !important; }
    .badge.bg-info { background: linear-gradient(45deg, #17a2b8, #6f42c1) !important; }

    /* 模态框美化 */
    .modal-header {
        background: linear-gradient(45deg, #4361ee, #3a0ca3);
        color: white;
    }

    .modal-header .btn-close {
        filter: invert(1);
    }
</style>
{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">活动管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <a href="{% url 'dashboard:category_management' %}" class="btn btn-success me-2">
            <i class="bi bi-tags"></i> 管理分类
        </a>
        <a href="{% url 'dashboard:admin_dashboard' %}" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-left"></i> 返回仪表盘
        </a>
    </div>
</div>

<!-- 拒绝原因模态框 -->
<div class="modal fade" id="rejectModal" tabindex="-1" aria-labelledby="rejectModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="rejectModalLabel">拒绝活动</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <p><strong>活动标题：</strong><span id="modal-activity-title"></span></p>
                    <p><strong>创建者：</strong><span id="modal-activity-creator"></span></p>
                </div>
                <div class="mb-3">
                    <label for="reject-reason" class="form-label">拒绝原因：</label>
                    <textarea class="form-control" id="reject-reason" rows="4"
                              placeholder="请详细说明拒绝此活动的原因..." required></textarea>
                    <div class="form-text">拒绝原因将发送给活动创建者</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirm-reject">确认拒绝</button>
            </div>
        </div>
    </div>
</div>

<!-- 搜索和筛选 -->
<div class="card shadow mb-4">
    <div class="card-body">
        <form method="get" class="row g-3">
            <div class="col-md-4">
                <input type="text" name="search" class="form-control" placeholder="搜索活动标题、描述或创建者..."
                       value="{{ search_query }}">
            </div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">所有状态</option>
                    <option value="pending" {% if status_filter == 'pending' %}selected{% endif %}>待审核</option>
                    <option value="approved" {% if status_filter == 'approved' %}selected{% endif %}>已通过</option>
                    <option value="rejected" {% if status_filter == 'rejected' %}selected{% endif %}>已拒绝</option>
                    <option value="cancelled" {% if status_filter == 'cancelled' %}selected{% endif %}>已取消</option>
                    <option value="completed" {% if status_filter == 'completed' %}selected{% endif %}>已完成</option>
                </select>
            </div>
            <div class="col-md-3">
                <select name="category" class="form-select">
                    <option value="">所有分类</option>
                    {% for category in categories %}
                    <option value="{{ category.id }}" {% if category_filter == category.id|stringformat:"i" %}selected{% endif %}>
                        {{ category.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">筛选</button>
            </div>
        </form>
    </div>
</div>

<!-- 活动列表 -->
<div class="card shadow">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>活动标题</th>
                        <th>创建者</th>
                        <th>分类</th>
                        <th>状态</th>
                        <th>参与人数</th>
                        <th>开始时间</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for activity in activities %}
                    <tr id="activity-{{ activity.id }}">
                        <td>{{ activity.id }}</td>
                        <td>
                            <a href="{% url 'activities:activity_detail' activity.id %}" target="_blank"
                               title="{{ activity.title }}">
                                {{ activity.title|truncatechars:30 }}
                            </a>
                        </td>
                        <td>
                            <a href="{% url 'dashboard:user_detail' activity.creator.id %}"
                               class="text-decoration-none">
                                {{ activity.creator.username }}
                            </a>
                        </td>
                        <td>{{ activity.category.name|default:"未分类" }}</td>
                        <td>
                            <span class="badge
                                {% if activity.status == 'approved' %}bg-success
                                {% elif activity.status == 'pending' %}bg-warning
                                {% elif activity.status == 'rejected' %}bg-danger
                                {% elif activity.status == 'completed' %}bg-info
                                {% else %}bg-secondary{% endif %}">
                                {{ activity.get_status_display }}
                            </span>
                        </td>
                        <td>
                            <span class="{% if activity.is_full %}text-danger{% endif %}">
                                {{ activity.current_participants }}/{{ activity.max_participants }}
                            </span>
                            {% if activity.is_full %}
                            <i class="bi bi-exclamation-triangle-fill text-warning" title="活动已满"></i>
                            {% endif %}
                        </td>
                        <td>{{ activity.start_time|date:"Y-m-d H:i" }}</td>
                        <td>{{ activity.created_at|date:"Y-m-d H:i" }}</td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                {% if activity.status == 'pending' %}
                                <button class="btn btn-success btn-approve" data-activity-id="{{ activity.id }}"
                                        title="批准活动">
                                    <i class="bi bi-check-lg"></i> 通过
                                </button>
                                <button class="btn btn-danger btn-reject"
                                        data-activity-id="{{ activity.id }}"
                                        data-activity-title="{{ activity.title }}"
                                        data-activity-creator="{{ activity.creator.username }}"
                                        title="拒绝活动">
                                    <i class="bi bi-x-lg"></i> 拒绝
                                </button>
                                {% endif %}
                                <a href="{% url 'activities:activity_detail' activity.id %}"
                                   class="btn btn-info" target="_blank" title="查看活动详情">
                                    <i class="bi bi-eye"></i>
                                </a>
                                <a href="{% url 'activities:activity_edit' activity.id %}"
                                   class="btn btn-warning" target="_blank" title="编辑活动"
                                   {% if activity.status == 'completed' %}disabled{% endif %}>
                                    <i class="bi bi-pencil"></i>
                                </a>
                                <button class="btn btn-danger btn-delete" data-activity-id="{{ activity.id }}"
                                        title="删除活动">
                                    <i class="bi bi-trash"></i> 删除
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="9" class="text-center text-muted py-4">
                            <i class="bi bi-inbox display-4 d-block mb-2"></i>
                            暂无活动数据
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        {% if activities.has_other_pages %}
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center">
                {% if activities.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ activities.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if status_filter %}&status={{ status_filter }}{% endif %}{% if category_filter %}&category={{ category_filter }}{% endif %}">上一页</a>
                </li>
                {% endif %}

                {% for num in activities.paginator.page_range %}
                    {% if activities.number == num %}
                    <li class="page-item active"><span class="page-link">{{ num }}</span></li>
                    {% else %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ num }}{% if search_query %}&search={{ search_query }}{% endif %}{% if status_filter %}&status={{ status_filter }}{% endif %}{% if category_filter %}&category={{ category_filter }}{% endif %}">{{ num }}</a>
                    </li>
                    {% endif %}
                {% endfor %}

                {% if activities.has_next %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ activities.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if status_filter %}&status={{ status_filter }}{% endif %}{% if category_filter %}&category={{ category_filter }}{% endif %}">下一页</a>
                </li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
    </div>
</div>

<!-- 统计信息 -->
<div class="row mt-4">
    <div class="col-md-3">
        <div class="card bg-primary text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4>{{ activities.count }}</h4>
                        <p class="mb-0">当前显示</p>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-list-ul fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-warning text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4>{{ pending_activities_count }}</h4>
                        <p class="mb-0">待审核</p>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-clock fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-success text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4>{{ approved_activities_count }}</h4>
                        <p class="mb-0">已通过</p>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-check-circle fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-info text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4>{{ total_participants }}</h4>
                        <p class="mb-0">总参与</p>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-people fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    let currentActivityId = null;
    const rejectModal = new bootstrap.Modal(document.getElementById('rejectModal'));

    // 拒绝按钮点击事件 - 打开模态框
    document.querySelectorAll('.btn-reject').forEach(btn => {
        btn.addEventListener('click', function() {
            currentActivityId = this.dataset.activityId;
            const activityTitle = this.dataset.activityTitle;
            const activityCreator = this.dataset.activityCreator;

            // 设置模态框内容
            document.getElementById('modal-activity-title').textContent = activityTitle;
            document.getElementById('modal-activity-creator').textContent = activityCreator;
            document.getElementById('reject-reason').value = '';

            // 显示模态框
            rejectModal.show();
        });
    });

    // 确认拒绝按钮
    document.getElementById('confirm-reject').addEventListener('click', function() {
    const rejectReason = document.getElementById('reject-reason').value.trim();

    if (!rejectReason) {
        alert('请填写拒绝原因');
        return;
    }

    // 显示加载状态
    const confirmBtn = this;
    const originalText = confirmBtn.innerHTML;
    confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';
    confirmBtn.disabled = true;

    // 发送拒绝请求 - 使用正确的URL
    const url = `{% url 'dashboard:reject_activity' 0 %}`.replace('0', currentActivityId);
    console.log('Sending request to:', url); // 调试信息

    fetch(url, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            reject_reason: rejectReason
        })
    })
    .then(response => {
        console.log('Response status:', response.status); // 调试信息
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Response data:', data); // 调试信息
        if (data.success) {
            // 关闭模态框
            rejectModal.hide();
            // 刷新页面
            location.reload();
        } else {
            alert('操作失败: ' + data.message);
            confirmBtn.innerHTML = originalText;
            confirmBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败，请重试: ' + error.message);
        confirmBtn.innerHTML = originalText;
        confirmBtn.disabled = false;
    });
});

    // 审核通过
    document.querySelectorAll('.btn-approve').forEach(btn => {
        btn.addEventListener('click', function() {
            const activityId = this.dataset.activityId;
            if (confirm('确定要通过这个活动吗？')) {
                fetch(`{% url 'dashboard:approve_activity' 0 %}`.replace('0', activityId), {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('操作失败，请重试');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('操作失败，请重试');
                });
            }
        });
    });

    // 删除活动
    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            const activityId = this.dataset.activityId;
            const activityTitle = this.closest('tr').querySelector('td:nth-child(2) a').title;

            if (confirm(`确定要删除活动 "${activityTitle}" 吗？\n\n此操作不可撤销，所有相关数据（报名、评论、评分等）都将被删除！`)) {
                fetch(`{% url 'dashboard:activity_delete' 0 %}`.replace('0', activityId), {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 从表格中移除该行
                        document.getElementById(`activity-${activityId}`).remove();

                        // 显示成功消息
                        const alertDiv = document.createElement('div');
                        alertDiv.className = 'alert alert-success alert-dismissible fade show mt-3';
                        alertDiv.innerHTML = `
                            <i class="bi bi-check-circle"></i> ${data.message}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        `;
                        document.querySelector('main').insertBefore(alertDiv, document.querySelector('main').firstChild);

                        // 更新统计信息
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败，请重试');
                });
            }
        });
    });

    // 添加键盘快捷键
    document.addEventListener('keydown', function(e) {
        // Ctrl + F 聚焦搜索框
        if (e.ctrlKey && e.key === 'f') {
            e.preventDefault();
            document.querySelector('input[name="search"]').focus();
        }
    });
});
</script>
{% endblock %}